<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row>
        <el-form-item label="巡检分类" required prop="category">
          <el-select v-model="formItem.category" clearable placeholder="请选择巡检分类" size="mini">
            <el-option v-for="(item) in categories" :key="item.code" :label="item.name " :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检项类别" required prop="itemType">
          <el-select v-model="formItem.itemType" clearable placeholder="请选择巡检项类别" size="mini">
            <el-option v-for="(item) in types" :key="item.code" :label="item.text " :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检项内容" required prop="item">
          <el-input v-model="formItem.item" placeholder="请输入巡检项内容" :maxlength="255" />
        </el-form-item>
        <el-form-item label="数据类型" required prop="dataType">
          <el-select v-model="formItem.dataType" clearable placeholder="请选择巡检项类别" size="mini">
            <el-option v-for="(item) in dataTypes" :key="item.code" :label="item.name " :value="item.code" @click.native="changeDataType(item)" />
          </el-select>
        </el-form-item>
        <el-form-item label="序号">
          <el-input-number v-model="formItem.sort" :min="0" :max="999999" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="formItem.unit" placeholder="请输入单位" :maxlength="255" />
        </el-form-item>
        <el-form-item label="异常判断规则">
          <el-input v-model="formItem.rule" placeholder="请输入异常判断规则" :maxlength="255" />
        </el-form-item>
        <el-form-item v-if="formItem.dataType==='number'" label="结果候选值" required>
          <el-input v-model="test" placeholder="输入候选值上限和下限即可，按回车添加" @change="add" />
          <div v-if="formItem.candidateValueArr.length > 0" class="fix-input-prefix2">
            <el-tag v-for="tag in formItem.candidateValueArr" :key="tag" size="mini" closable type="success" @close="removeUser(tag)">{{ tag }}</el-tag>
            <i class="el-icon-close" title="清除所有值" @click="clearCandidate" />
          </div>
        </el-form-item>
        <el-form-item label="规则状态">
          <el-radio-group v-model="formItem.disabled">
            <el-radio :label="false">启用</el-radio>
            <el-radio :label="true">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { create, update, detail } from '@neu/dcom-ui/api/hnInspectionItem'
import { clone } from '@neu/biz-core/utils/utils'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'

// 定义一个表单原始项
const formItem = {
  // 分类
  category: '',
  // 巡检项类别
  itemType: '',
  //  巡检内容
  item: '',
  // 巡检项数据类型
  dataType: '',
  // 单位
  unit: '',
  // 排序
  sort: 0,
  // 候选值
  candidateValue: '',
  candidateValueArr: [],
  // 异常判断准则
  rule: '',
  // 是否禁用
  disabled: false
}
export default {
  name: 'HnInspectionEdit',
  components: {
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      test: '',
      content: null,
      editorOption: {},
      types: [],
      dataTypes: [{ name: '单选', code: 'select' }, { name: '整数', code: 'number' }],
      categories: [{ name: '日巡检', code: 'day' }, { name: '定期健康巡检', code: 'regular' }, { name: '重保服务', code: 'service' }],
      // 编辑的表单内容
      formItem: clone(formItem),
      // 表单验证规则
      rules: {
        category: [{ required: true, message: '不能为空', trigger: 'change' }],
        itemType: [{ required: true, message: '不能为空', trigger: 'change' }],
        item: [{ required: true, message: '不能为空', trigger: 'blur' }],
        dataType: [{ required: true, message: '不能为空', trigger: 'change' }]
        // rule: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('hnInspectionItemType').then(res => {
      if (res.status === 'success') {
        this.types = res.data
      }
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (this.formItem.candidateValueArr.length === 0) {
              return this.$message({
                showClose: true,
                message: '候选值不能为空',
                type: 'error'
              })
            }
            if (this.formItem.dataType === 'number') {
              for (const t of this.formItem.candidateValueArr) {
                if (Number.isNaN(Number(t))) {
                  return this.$message({
                    showClose: true,
                    message: '候选值必须为数值',
                    type: 'error'
                  })
                }
              }
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.candidateValueArr = this.formItem.candidateValueArr.filter(t => {
        return t !== tag
      })
    },
    /** 删除所有项 */
    clearCandidate() {
      this.formItem.candidateValueArr = []
    },
    add(value) {
      if (!this.formItem.candidateValueArr.includes(value)) {
        this.formItem.candidateValueArr.push(value)
        this.test = ''
      }
    },
    changeDataType(item) {
      debugger
      if (item.code === 'select') {
        this.formItem.candidateValueArr = ['正常', '异常']
      } else {
        this.formItem.candidateValueArr = []
      }
    }
  }
}
</script>

